<?php

declare(strict_types=1);

namespace app\api\controller;

use app\model\Domain as ModelDomain;
use app\model\DomainVisit;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;

class Domain
{
    public function scan()
    {
        // 每次执行可处理100条数据
        // 每小时处理一次，每天可处理24000条数据
        $list_domain = ModelDomain::order('last_scan_time asc')
            ->limit(100)
            ->select();
        $client = new Client();
        $promises = [];
        foreach ($list_domain as $domain) {
            $promises[$domain->id] = $client->getAsync($domain->domain . '/visit.html');
            $domain->last_scan_time = time();
            $domain->scan_times++;
            $domain->save();
        }

        // Wait on all of the requests to complete.
        $results = Promise\Utils::settle($promises)->wait();

        foreach ($results as $key => $result) {
            DomainVisit::create([
                'domain_id' => $key,
                'result_code' => $result['state'],
            ]);
            // TODO：记录失败原因
        }
    }
}
